package com.weiaibenpao.demo.chislim.ui.activity.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.bean.UserDataBean;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.presenter.LoginPresenter;
import com.weiaibenpao.demo.chislim.ui.activity.MainActivity;
import com.weiaibenpao.demo.chislim.ui.activity.me.CompleteInfoActivity;
import com.weiaibenpao.demo.chislim.utils.SystemUtil;
import com.weiaibenpao.demo.chislim.utils.Utils;
import com.weiaibenpao.demo.chislim.view.LoginView;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

import static com.umeng.socialize.bean.SHARE_MEDIA.QQ;

public class LoginActivity extends BaseActivity<LoginView, LoginPresenter> implements LoginView {

    @BindView(R.id.login_qq)
    ImageView loginQq;
    @BindView(R.id.login_wx)
    ImageView loginWx;
    @BindView(R.id.login_sign)
    ImageView loginSign;
    @BindView(R.id.userPhone)
    EditText userPhone;
    @BindView(R.id.userCode)
    EditText userCode;
    @BindView(R.id.sendCode)
    TextView sendCode;
    @BindView(R.id.myLogin)
    Button myLogin;
    /**
     * 登陆类型
     * type=0 第三方
     * type=1 手机号码登陆
     */
    private int type;
    UserPreferences userPreferences;
    private String openId, imgUrl, screenName, registerSource,gender;

    /**
     * 首先获取UMShareAPI
     */
    UMShareAPI mShareAPI;


    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_login;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        userPreferences = UserPreferences.getInstance();
        /**
         * 首先获取UMShareAPI
         */
        mShareAPI = UMShareAPI.get(this);
        initShareAPI(savedInstanceState);
        //微博的回调地址
        // Config.REDIRECT_URL = "http://www.chislim.com";
    }

    /**
     * 第三方登陆
     */
    private void initShareAPI(Bundle savedInstanceState) {

        mShareAPI.fetchAuthResultWithBundle(this, savedInstanceState, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                Toast.makeText(getApplicationContext(), "onRestoreInstanceState Authorize succeed", Toast.LENGTH_SHORT).show();
//                switch (platform) {
//                        case QQ:
//                            openId = data.get("openid");
//                            screenName = data.get("screen_name");
//                            imgUrl = data.get("profile_image_url");
//                            registerSource = "QQ";
////                            userPreferences.putString(USER_NAME, map.get("screen_name"));
////                            userPreferences.putString(USER_AVATAR, map.get("profile_image_url"));
////                            userPreferences.putString(USER_OPENID, map.get("openid"));
////                            userPreferences.putString(USER_SOURCE, "QQ");
////                            Log.e("ljb", map.toString());
////                            mPresenter.loginByThree(map.get("openid"), "QQ", JPushInterface.getRegistrationID(getApplicationContext())
////                                    , SystemUtil.getSystemModel());
//                            break;
//                        case SINA:
//                            openId = data.get("id");
//                            screenName = data.get("screen_name");
//                            imgUrl = data.get("profile_image_url");
//                            registerSource = "weibo";
////                            userPreferences.putString(USER_NAME, map.get("screen_name"));
////                            userPreferences.putString(USER_AVATAR, map.get("profile_image_url"));
////                            userPreferences.putString(USER_OPENID, map.get("id"));
////                            userPreferences.putString(USER_SOURCE, "weibo");
////                            mPresenter.loginByThree(map.get("openid"), "weibo", JPushInterface.getRegistrationID(getApplicationContext())
////                                    , SystemUtil.getSystemModel());
//                            break;
//                        case WEIXIN:
//
//                            openId = data.get("unionid");
//                            screenName = data.get("screen_name");
//                            imgUrl = data.get("profile_image_url");
//                            registerSource = "weixin";
//                            break;
//
//                    }
//                    mPresenter.loginByThree(openId, registerSource, JPushInterface.getRegistrationID(getApplicationContext()), SystemUtil.getSystemModel());

            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                Toast.makeText(getApplicationContext(), "onRestoreInstanceState Authorize onError", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                Toast.makeText(getApplicationContext(), "onRestoreInstanceState Authorize onCancel", Toast.LENGTH_SHORT).show();

            }
        });
    }

    public static void startSelf(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @OnClick({R.id.login_qq, R.id.login_wx, R.id.login_sign, R.id.sendCode, R.id.myLogin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_qq:

                /*获取客户端安装信息*/
                boolean qqBoolean = mShareAPI.isInstall(this, QQ);
        /*选取需要授权的平台，并进行授权，其中umAuthLisrener是回调监听器*/
                if (qqBoolean) {
                    registerSource = "QQ";
                    mShareAPI.doOauthVerify(this, SHARE_MEDIA.QQ, authListener);
                } else
                    Toast.makeText(this, "请安装QQ客户端", Toast.LENGTH_SHORT).show();

                break;
            case R.id.login_wx:
                //判断是否安装了客户端
                boolean wxBoolean = mShareAPI.isInstall(this, SHARE_MEDIA.WEIXIN);
        /*选取需要授权的平台，并进行授权，其中umAuthLisrener是回调监听器*/
                if (wxBoolean) {
                    registerSource = "WEIXIN";
                    mShareAPI.doOauthVerify(this, SHARE_MEDIA.WEIXIN, authListener);
                } else
                    Toast.makeText(this, "请安装微信户端", Toast.LENGTH_SHORT).show();

                break;
            case R.id.login_sign:
                /*获取客户端安装信息*/
                boolean wbBoolean = mShareAPI.isInstall(this, SHARE_MEDIA.SINA);
        /*选取需要授权的平台，并进行授权，其中umAuthLisrener是回调监听器*/
                if (wbBoolean) {
//                    UmengTool.getSignature(this);
                    registerSource = "SINA";
                    mShareAPI.doOauthVerify(this, SHARE_MEDIA.SINA, authListener);
                } else
                    Toast.makeText(this, "请安装新浪微博客户端", Toast.LENGTH_SHORT).show();


                break;
            case R.id.sendCode:
                if (checkPhone()) {
                    //发送短信验证码
                    Log.i("ljb", userPhone.getText().toString().trim());
                    mPresenter.getSeedCode(userPhone.getText().toString().trim());
                }
                break;
            case R.id.myLogin:
                //登录
                type = 1;
                goLogin();
                break;
        }
    }

    /**
     * 授权监听
     */
    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onComplete(final SHARE_MEDIA platform, int action, final Map<String, String> data) {



            mShareAPI.getPlatformInfo(LoginActivity.this, platform, new UMAuthListener() {
                @Override
                public void onStart(SHARE_MEDIA share_media) {

                }

                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                    openId = map.get("uid");
                    screenName = map.get("name");
                    imgUrl = map.get("iconurl");
                    gender=map.get("gender");
                    Logger.e("imgUrl:"+imgUrl);
                    mPresenter.loginByThree(openId, registerSource, JPushInterface.getRegistrationID(getApplicationContext()), SystemUtil.getSystemModel());

                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {

                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "onRestoreInstanceState Authorize onCancel", Toast.LENGTH_SHORT).show();

        }
    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);

    }
    private void goLogin() {
        if (!TextUtils.isEmpty(userCode.getText().toString().trim()) && !TextUtils.isEmpty(userPhone.getText().toString())) {

            mPresenter.loginByPhone(userPhone.getText().toString().trim(), userCode.getText().toString().trim(),
                    JPushInterface.getRegistrationID(getApplicationContext())
                    , SystemUtil.getSystemModel());
        }else {
            Toast.makeText(this,"请输入正确的信息",Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 电话号码验证
     */
    private TimeCount countDown;
    public boolean checkPhone(){
        //判断手机号码是否为空
        if (!TextUtils.isEmpty(userPhone.getText().toString())) {
            //验证手机号码的正确性
            if (Utils.isMobileNO(userPhone.getText().toString().trim())) {
                //60秒倒计时
                countDown = new TimeCount(60000, 1000);
                countDown.start();
                return true;
            } else {/**/
                Toast.makeText(this, this.getResources().getString(R.string.input_rightphone_text), Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            Toast.makeText(this, this.getResources().getString(R.string.input_newphone_text), Toast.LENGTH_SHORT).show();
            return false;
        }
    }


    @Override
    public void upDataInfoSuccess(UserBean userBean) {

    }

    @Override
    public void loginSuccess(UserDataBean userDataBean) {

        /**
         * getRegisterView ==1 表示 此用户已经是老用户  直接跳转主页
         *                 ==0 表示是新用过户  需要完善信息
         */
        if (userDataBean.getUser() != null) {
            if (!TextUtils.isEmpty(userDataBean.getUser().getUserPhone())){
                userPreferences.putUserData(userDataBean.getUser(), true);
                MainActivity.startSelf(this);
           }else {
                BindingActivity.startSelf(this,openId,registerSource);

            }
        } else {
            userPreferences.putString(UserPreferences.USER_NAME, screenName);
            userPreferences.putString(UserPreferences.USER_AVATAR, imgUrl);
            userPreferences.putString(UserPreferences.USER_SEX, gender);
               if (type==1){
                   CompleteInfoActivity.startSelf(this);
               }else {
                   BindingActivity.startSelf(this,openId,registerSource);
               }
        }
        finish();

    }


    @Override
    public void seedSuccess(String str) {

    }

    @Override
    public LoginPresenter initPresenter() {
        return new LoginPresenter();
    }

    /**
     * 60秒倒计时
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            sendCode.setClickable(false);
            sendCode.setText(getApplication().getResources().getString(R.string.show_verify_text) + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
            sendCode.setText(getApplication().getResources().getString(R.string.get_repeatverify_text));
            sendCode.setClickable(true);
        }
    }


    @Override
    protected void onDestroy() {
        if(countDown != null){
            countDown.cancel();
        }
        UMShareAPI.get(this).release();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }
}
